package com.jlz.actions.console.valuetype;

import java.util.List;

import org.apache.struts2.convention.annotation.Standard;
import org.springframework.beans.factory.annotation.Autowired;

import com.jlz.beans.def.ValuetypeBean;
import com.jlz.managers.def.ValueLabel;
import com.jlz.managers.def.Valuetypes;

@Standard(rest={"valuetypeId", "action", "valueLabel.value"})
public class LabelsAction {
	@Autowired Valuetypes valuetypes;
	int valuetypeId;
	String action;
	ValueLabel valueLabel = new ValueLabel();
	ValuetypeBean valuetype = null;
	List<ValueLabel> valueLabels = null;
	public String execute(){
		valuetype = valuetypes.get(valuetypeId);
		valueLabels = valuetype.getValueLabels();
		//
		switch(action.charAt(0)){
		case 'a'://add
			if(!add())return "edit";
			break;
		case 'r'://remove
			if(!remove())return "edit";
			break;
		case 'u'://up
			if(!changeidx(-1))return "edit";
			break;
		case 'd'://down
			if(!changeidx(1))return "edit";
			break;
		}
		//
		valuetype.resetValueLabels();
		valuetypes.update(valuetype);
		return "edit";
	}
	private ValueLabel _find(){
		for(ValueLabel p: valueLabels){
			if(p.A.equals(valueLabel.A))return p;
		}
		return null;
	}
	
	private boolean add(){
		ValueLabel p = _find();
		if(p == null){
			valueLabels.add(valueLabel);
		}else{
			p.B = valueLabel.B;
		}
		return true;
	}
	
	public boolean remove(){
		ValueLabel p = _find();
		if(p == null)return false;
		valueLabels.remove(p);
		return true;
	}
	
	//TODO 非线程安全的写法
	public boolean changeidx(int step){
		for(int i = (step==1?0:valueLabels.size() - 1) ;
			i >=0 && i < valueLabels.size(); i += step){
			if(valueLabels.get(i).A.equals(valueLabel.A)){
				i += step;
				if(i < 0 || i >= valueLabels.size()){return false;}
				valueLabel = valueLabels.remove(i - step);
				valueLabels.add(i, valueLabel);
				return true;
			}
		}
		return false;
	}
	
	public ValuetypeBean getValuetype(){
		return valuetype;
	}
	
	///
	public int getValuetypeId() {
		return valuetypeId;
	}
	public void setValuetypeId(int valuetypeId) {
		this.valuetypeId = valuetypeId;
	}
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}
	public ValueLabel getValueLabel() {
		return valueLabel;
	}
	public void setValueLabel(ValueLabel pair) {
		this.valueLabel = pair;
	}
	
}
